
// 上传文件
export function uploadFile(file, paperId) {
  return new Promise((resolve) => {
    const formData = new FormData();
    formData.append("file", file, file.name);
    uploadApi(formData, paperId).then(async (res) => {
      const uri = `${getProjectApi("file")}${res.data}`;
      const url = `${getProjectApi("file")}${res.data}?mediaType=${file.type}`;
      if(/^(video|audio)/gi.test(file.type)) {
        const res = await fetch(uri)
        const blobUrl = URL.createObjectURL(await res.blob())
        resolve({uri, url, blobUrl});
      } else {
        resolve(url);
      }
    });
  });
}
/**
 * 选择文件
 * @param { string } accept 文件类型
 * @param {*} callback
 */
export function changeFile(accept, callback = Function) {
  const input = document.createElement("input");
  input.type = "file";
  input.style = "display: none";
  input.accept = accept;
  input.click();
  input.onchange = async function (event) {
    const file = event.target.files[0];
    callback(file);
    input.remove();
  };
}

/**
 * 文件上传插件
 * @param { string } name 插件名称
 * @param { string } text 菜单名称
 * @param {*} accept
 * @param {*} callback
 * @returns
 */
export function registerChangeFileBtn(options = {}) {
  const {
    name, // 按钮名称
    text = "",
    icon,
    accept = ".doc,.docx",
    success = Function,
  } = options;
  return function (editor, paperId) {
    editor.ui.registry.addButton(name, {
      text: text,
      icon: icon,
      onAction: function () {
        changeFile(accept, (file) => success(editor, file, paperId));
      },
    });
  };
}
// 答题项
function radioItem(radioName, label, value) {
  const html = `<div style="display:flex;align-items: center;height:30px;margin-right:20px;" id="radioItem">
  <input type="radio" style="margin:0 5px;" name="${radioName}" value="${value}"></input>
  <span>${label}</span>
  </div>`;
  return html;
}
export default {
  /**
   * 复制文本
   * @param {*} editor
   */
  powerPaste: (editor) => {
    editor.on("paste", function (e) {
      // 只处理来自剪贴板的数据
      if (e.clipboardData) {
        // 清除默认粘贴行为
        e.preventDefault();
        // 将处理后的内容插入编辑器
        editor.insertContent(e.clipboardData.getData("text/html"));
      }
    });
  },
  // 输入框
  insertInput: (editor) => {
    editor.ui.registry.addButton('insertInput', {
      text: '',
      tooltip: "点击插入输入框",
      icon: 'edit-block',
      onAction: function () {
        const htmlContent = `<input id="input" placeholder="请输入内容" style="width:100px;max-width:max-content;" value="" />`;
        editor.execCommand("mceInsertContent", false, htmlContent);
      },
    });
  },
  // 斜线拆分单元格
  splitBorder: (editor) => {
    editor.ui.registry.addButton('splitBorder', {
      text: '',
      tooltip: "点击斜线拆分单元格",
      icon: 'color-swatch-remove-color',
      onAction: function () {
        const selectionNode = editor.selection.getNode()
        selectionNode.style.padding = '0'
        selectionNode.style.height = '50px'
        selectionNode.style.width = 'auto'
        selectionNode.style.textAlign = 'center'
        selectionNode.style.overflow = 'hidden'
        selectionNode.style.borderCollapse = 'collapse';
        const br = selectionNode.querySelector('br')
        br && br.remove()
        const cellBoxStyle = `width: 100%;height: 100%;overflow: hidden;position: relative;padding: 5px 10px;`
        const cellYStyle = `margin-left: 50%;height: 50%;`
        const cellXStyle = `margin-left: -50%;height: 50%;`
        // 使用 position:  absolute; 定位时前面需加/* absolute */防止被替换
        const splitStyle = `/* absolute */position:  absolute;top: 55%;left: -5%;width: 110%;height: 1px;background: #333;transform: rotate(20deg);`
        editor.selection.setContent('')
        editor.selection.setContent(`<div id="cell-split" style="${cellBoxStyle}">
              <div style="${cellYStyle}"></div>
              <div style="${cellXStyle}"></div>
              <div style="${splitStyle}"></div>
        </div>`)
        editor.EditorMode.deactivate()
      },
    });
  },
  /**
   * 导入word
   * @param {*} editor
   */
  importWord: registerChangeFileBtn({
    name: "importWord",
    text: "上传Word",
    icon: "browse",
    accept: ".doc,.docx",
    success: (editor, file) => {
      convertToHtml({ arrayBuffer: file }).then((result) => {
        const htmlContent = result.value;
        editor.execCommand("mceInsertContent", false, htmlContent);
      });
    },
  }),
  // 上传图片
  UploadImage: registerChangeFileBtn({
    name: "UploadImage",
    text: "",
    icon: "image",
    accept: "image/*",
    success: (editor, file, paperId) => {
      uploadFile(file, paperId).then((url) => {
        // const maxWidth = editor.getBody().clientWidth
        // const htmlContent = `<img style="max-width: ${maxWidth}px;height:auto;object-fit: contain;" src="${url}"/>`;
        const htmlContent = `<img style="width: 150px;height:150px;object-fit: contain;" src="${url}"/>`;
        editor.execCommand("mceInsertContent", false, htmlContent);
      });
    },
  }),
  // 上传视频
  UploadVideo: registerChangeFileBtn({
    name: "UploadVideo",
    text: "",
    icon: "embed",
    accept: "video/*",
    success: (editor, file, paperId) => {
      uploadFile(file, paperId).then(({uri, url, blobUrl}) => {
        const htmlContent = `<video style="width: 300px;height:225px;" controls controlsList="nodownload" data-uri="${uri}" data-url="${url}" name="media" src="${blobUrl}"></video>`;
        // editor.insertContent(htmlContent);
        editor.execCommand("mceInsertContent", false, htmlContent);
      });
    },
  }),
  // 上传音频
  UploadAudio: registerChangeFileBtn({
    name: "UploadAudio",
    text: "",
    icon: 'music',
    accept: ".mp3",
    success: (editor, file, paperId) => {
      uploadFile(file, paperId).then(({uri, url, blobUrl}) => {
        const htmlContent = `<audio  style="width: 300px;height:50px;" controls controlsList="nodownload" data-uri="${uri}" data-url="${url}" src="${blobUrl}" type="${file.type}"></audio>`;
        editor.insertContent(htmlContent);
      });
    },
  }),
  // 上传文件
  UploadFile: registerChangeFileBtn({
    name: "UploadFile",
    text: "",
    icon: "browse",
    accept: "*",
    success: (editor, file, paperId) => {
      uploadFile(file, paperId).then((url) => {
        const htmlContent = `<a href="${url}" download="${file.name}">${file.name}</a>`;
        editor.insertContent(htmlContent);
      });
    },
  }),
  // 自定义单选按钮组
  RadioButtonGroup: (editor) => {
    let now = null;
    editor.ui.registry.addSplitButton("RadioButtonGroup", {
      text: "添加答题项",
      tooltip: "点击添加表演形式后，选择添加子选项",
      onAction: () => {
        now = Date.now();
        const html = `<div id="RadioButtonGroupBox" style="display:flex;flex-direction: column;width:90%;min-height: 30px;border:1px solid #ccc;" data-now="${now}">
        <div id="RadioButtonGroup" style="display:flex;width:100%;" data-id="${now}"></div>
        <div style="" id="RadioButtonContent"></div>
        </div><div></br></div>`;
        editor.selection.getNode().remove()
        editor.selection.setContent(html)
        editor.focus()
        // editor.insertContent(html);
        // const range = document.createRange();
        // const htmlDom = range.createContextualFragment(html);
        // editor.getBody().append(htmlDom);
      },
      onItemAction: (api, value) => {
        const el = editor.getDoc();
        const targetDoc = el.querySelector(`div[data-id="${now}"]`);
        targetDoc.innerHTML += value;
      },
      fetch: function (callback) {
        var items = [
          {
            type: "choiceitem",
            text: "录音",
            value: radioItem(now, "录音", "record"),
          },
          {
            type: "choiceitem",
            text: "视频",
            value: radioItem(now, "视频", "video"),
          },
          {
            type: "choiceitem",
            text: "拍照",
            value: radioItem(now, "拍照", "image"),
          },
          {
            type: "choiceitem",
            text: "文件上传",
            value: radioItem(now, "文件上传", "upload-file"),
          },
        ];
        callback(items);
      },
    });
  },
};
